package com.mvetc.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.mvetc.entity.Country;
import com.mvetc.service.CountryService;
import com.mvetc.service.impl.CountryServiceImpl;

/**
 * Servlet implementation class CountryServlet
 */
@WebServlet("/CountryServlet")
public class CountryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
     
	private CountryService countryService = new CountryServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CountryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op = request.getParameter("op");
		if (op == null || "getCountryList".equals(op)) {
			doGetCountryList(request,response);
		}
	}

	private void doGetCountryList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String countryId = request.getParameter("countryId");
		String countryName = request.getParameter("countryName");
		Map<String, String> map = new HashMap<>();
		map.put("countryId", countryId);
		map.put("countryName", countryName);
		List<Country> countries = countryService.getBy(map);
		
		Gson gson = new Gson();
		String jsonObject = gson.toJson(countries);
		
		response.setContentType("application/json");
		response.getWriter().write(jsonObject);
	}

}
